package main

import (
	"context"
	"flag"
	"github.com/coreos/etcd/clientv3"
	"go.etcd.io/etcd/clientv3/concurrency"
	"log"
	"strings"
	"time"
)

var (
	addr     = flag.String("addr", "http://127.0.0.1:2379", "etcd addresss")
	lockName = flag.String("name", "mylock", "lock name")
)

func main() {
	flag.Parse()
	endpoints := strings.Split(*addr, ",")
	cli, err := clientv3.New(clientv3.Config{Endpoints: endpoints})
	if err != nil {
		log.Fatal(err)
	}
	defer cli.Close()
	userLock(cli) //测试锁
}

func userLock(cli1 *clientv3.Client) {
	//为锁生成session
	session, err := concurrency.NewSession(cli1)
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()
	m := concurrency.NewMutex(session, *lockName)
	ctx := context.TODO()
	//  请求锁
	log.Println("acquiring lock")
	m.Lock(ctx)
	log.Println("acquired lock")

	time.Sleep(time.Duration(10 * time.Second))
	m.Unlock(ctx) //释放锁
	log.Println("released lock")
}
